package com.nationart.backend.config;


import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.Filter;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

import com.nationart.backend.shiro.RedisSessionDAO;
import com.nationart.backend.shiro.ShiroRealm;
import com.nationart.backend.shiro.ShiroWebSessionManager;
import com.nationart.backend.shiro.filter.LoginFilter;

import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class ShiroConfiguration {

	 @Value("${spring.redis.shiro.host}")
	    private String host;
	    @Value("${spring.redis.shiro.port}")
	    private int port;
	    @Value("${spring.redis.shiro.timeout}")
	    private int timeout;
//	    @Value("${spring.redis.shiro.password}")
//	    private String password;
	    @Value("${spring.redis.shiro.jedis.pool.maxIdle}")
	    private int maxIdle;
	 
	    @Value("${spring.redis.shiro.jedis.pool.maxTotal}")
	    private int maxTotal;
	    
	    @Value("${spring.redis.shiro.jedis.pool.minIdle}")
	    private int minIdle;
	    
	    @Value("${spring.redis.shiro.jedis.pool.maxWaitMillis}")
	    private int maxWaitMillis;
	    @Bean
	    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {

	        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
	        shiroFilterFactoryBean.setSecurityManager(securityManager);
	        Map<String, Filter> filters = new LinkedHashMap<String, Filter>();
	        filters.put("authc", new LoginFilter());
	        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
	        //注意过滤器配置顺序 不能颠倒
	        //配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了，登出后跳转配置的loginUrl
	        filterChainDefinitionMap.put("/api/**", "anon");
	        filterChainDefinitionMap.put("/sys/login", "anon");
	        filterChainDefinitionMap.put("/**/*.css", "anon");
	        filterChainDefinitionMap.put("/**/*.js", "anon");
	        filterChainDefinitionMap.put("/**/*.html", "anon");
	        filterChainDefinitionMap.put("/img/**", "anon");
	        filterChainDefinitionMap.put("/fonts/**", "anon");
	        filterChainDefinitionMap.put("/plugins/**", "anon");
	        filterChainDefinitionMap.put("/swagger/**", "anon");
	        filterChainDefinitionMap.put("/favicon.ico", "anon");
	        filterChainDefinitionMap.put("/captcha.jpg", "anon");
	        filterChainDefinitionMap.put("/sys/**", "authc");
	        filterChainDefinitionMap.put("/", "anon");
	        shiroFilterFactoryBean.setFilters(filters);
	        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
	        return shiroFilterFactoryBean;
	    }
	 
	    /**
	     * 凭证匹配器
	     * （由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了
	     * ）
	     *
	     * @return
	     */
	    @Bean
	    public HashedCredentialsMatcher hashedCredentialsMatcher() {
	        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
	        hashedCredentialsMatcher.setHashAlgorithmName(Sha256Hash.ALGORITHM_NAME);//散列算法
	        return hashedCredentialsMatcher;
	    }
	 
	    @Bean
	    public ShiroRealm myShiroRealm() {
	    	ShiroRealm myShiroRealm = new ShiroRealm();
	        myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
	        return myShiroRealm;
	    }
	 
	 
	    @Bean
	    public SecurityManager securityManager() {
	        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
	        securityManager.setRealm(myShiroRealm());
	        // 自定义session管理 使用redis
	        securityManager.setSessionManager(sessionManager());
	        return securityManager;
	    }
	    
	    
	    @Bean
	    public DefaultWebSessionManager sessionManager() {
	        ShiroWebSessionManager mySessionManager = new ShiroWebSessionManager();
	        mySessionManager.setSessionDAO(redisSessionDAO());
	        return mySessionManager;
	    }
	    
	    /**
	     * 配置shiro redisManager
	     * <p>
	     * 使用的是shiro-redis开源插件
	     *
	     * @return
	     */
	    @Bean
	    public RedisTemplate<String,Object> redisTemplate() {
	    	RedisTemplate<String,Object> redisTemplate = new RedisTemplate<String,Object>();
	    	redisTemplate.setConnectionFactory(jedisConnectionFactory());
	        return redisTemplate;
	    }
	    /**
	     * RedisSessionDAO shiro sessionDao层的实现 通过redis
	     * <p>
	     * 
	     */
	    @Bean
	    public RedisSessionDAO redisSessionDAO() {
	        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
	        redisSessionDAO.setRedisTemplate(redisTemplate());
	        return redisSessionDAO;
	    }
	    
	    @Bean
	    public JedisPoolConfig jedisPoolConfig() {
	    	JedisPoolConfig config = new JedisPoolConfig();
	    	config.setMaxTotal(maxTotal);
	    	config.setMaxIdle(maxIdle);
	    	config.setMinIdle(minIdle);
	    	config.setMaxWaitMillis(maxWaitMillis);
	    	return config;
	    }
	    
	    @Bean
	    public JedisConnectionFactory jedisConnectionFactory() {
	    	JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
	    	connectionFactory.setPoolConfig(jedisPoolConfig());
	    	connectionFactory.setPort(port);
	    	connectionFactory.setHostName(host);
	    	connectionFactory.setUsePool(true);
	    	connectionFactory.setTimeout(timeout);
	    	connectionFactory.setDatabase(1);
	    	return connectionFactory;
	    }
	 
	    /**
	     * 开启shiro aop注解支持.
	     * 使用代理方式;所以需要开启代码支持;
	     *
	     * @param securityManager
	     * @return
	     */
	    @Bean
	    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
	        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
	        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager());
	        return authorizationAttributeSourceAdvisor;
	    }
}
